#include <QByteArray>
#include <QDialogButtonBox>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>
#include <QPixmap>
#include <QPushButton>

#include "caddsectiondialog.h"
#include "ui_caddsectiondialog.h"

CAddSectionDialog::CAddSectionDialog(QString parent_id, QString parent_name, QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::CAddSectionDialog), m_parent(parent_id), m_item(0)
{
    m_ui->setupUi(this);

    m_model = new CIconSelectionModel();
    m_ui->listView->setModel(m_model);

    if(parent_name.length())
        setWindowTitle(tr("Subsection of %1").arg(parent_name));
    else
        setWindowTitle(tr("Root"));

    connect(m_ui->browseBtn, SIGNAL(clicked()), this, SLOT(openFile()));

    connect(this, SIGNAL(rejected()), this, SLOT(deleteLater()));
    connect(this, SIGNAL(accepted()), this, SLOT(process()));

    connect(m_ui->listView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(checkFields()));
    connect(m_ui->nameEdit, SIGNAL(textChanged(QString)), this, SLOT(checkFields()));
    connect(m_ui->pathEdit, SIGNAL(textChanged(QString)), this, SLOT(checkFields()));
    connect(m_ui->toolBox, SIGNAL(currentChanged(int)), this, SLOT(checkFields()));

    checkFields();
}

CAddSectionDialog::~CAddSectionDialog()
{
    delete m_ui;
    delete m_model;
}

void CAddSectionDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

QVariant CAddSectionDialog::iconName()
{
    if(!m_ui->listView->currentIndex().isValid())
        return QVariant();

    int row = m_ui->listView->currentIndex().row();
    return m_model->nameById(row);
}

QVariant CAddSectionDialog::icon()
{
    if(!m_ui->pathEdit->text().length())
    {
        if(m_item)
            return m_item->icon();
        return QVariant();
    }

    QFile file(m_ui->pathEdit->text());
    if(!file.open(QIODevice::ReadOnly))
    {
        debug("Can't read");
        return QVariant();
    }

    return file.readAll();
}

QString CAddSectionDialog::id()
{
    if(m_item)
        return m_item->id();

    QCryptographicHash hash(QCryptographicHash::Md5);

    QUuid salt = QUuid::createUuid();

    QString str = QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz") + salt.toString();
    QByteArray arr = str.toLatin1();

    hash.addData(arr);

    arr = hash.result();

    return QString(arr.toHex()).toUpper();
}

QString CAddSectionDialog::name()
{
    return m_ui->nameEdit->text();
}

void CAddSectionDialog::checkFields()
{
    bool result = m_ui->nameEdit->text().length() &&
                  ((!m_ui->toolBox->currentIndex() && m_ui->listView->currentIndex().isValid())
                   || (m_ui->toolBox->currentIndex() && m_ui->pathEdit->text().length()));

    m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(result);
}

void CAddSectionDialog::process()
{
    m_map.clear();

    if(!m_item || m_ui->nameEdit->text()!=m_item->name().toString())
        m_map.insert(CTreeItem::getStringById(CTreeItem::Name), m_ui->nameEdit->text().toUtf8());

    if(!m_item)
        m_map.insert(CTreeItem::getStringById(CTreeItem::Parent), m_parent);
    
    if(!m_item)
    {
        m_map.insert(CTreeItem::getStringById(CTreeItem::Id), id());
    }

    if(!m_ui->toolBox->currentIndex())
    {
        if(!m_ui->listView->currentIndex().isValid())
            m_map.insert(CTreeItem::getStringById(CTreeItem::IconId), QString());
        else
        {
            int row = m_ui->listView->currentIndex().row();
            m_map.insert(CTreeItem::getStringById(CTreeItem::IconId), m_model->nameById(row));
            if(m_item)
                m_map.insert(CTreeItem::getStringById(CTreeItem::Icon), QVariant());
        }
    }
    else
    {
        if(m_ui->pathEdit->text().length())
        {
            QFile file(m_ui->pathEdit->text());
            if(file.open(QIODevice::ReadOnly))
            {
                QByteArray data;
                QBuffer buf(&data);
                buf.open(QIODevice::WriteOnly);

                QPixmap pix;
                pix.loadFromData(file.readAll());
                if(pix.width()>pix.height())
                    pix.scaledToWidth(16).save(&buf, "PNG");
                else
                    pix.scaledToHeight(16).save(&buf, "PNG");

                buf.close();

                m_map.insert(CTreeItem::getStringById(CTreeItem::Icon), data);

                file.close();
            }
            else
                debug("Can't open file. Reason: " + file.errorString());
        }
        else
            m_map.insert(CTreeItem::getStringById(CTreeItem::Icon), m_item->icon());
    }


    // TODO: write processing of else fields

    emit cathegory(this);
}

QStringList CAddSectionDialog::blobs()
{
    QStringList result;

//    if(m_map.contains(CTreeItem::getStringById(CTreeItem::Icon)))
        result << "*" + CTreeItem::getStringById(CTreeItem::Icon);

//    if(m_map.contains(CTreeItem::getStringById(CTreeItem::Name)))
        result << CTreeItem::getStringById(CTreeItem::Name);

    debug("Blobs: " + result.join("\n"));

    return result;
}

void CAddSectionDialog::openFile()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Choose image file"), "", tr("Images (*.png *.jpg *.gif)"));
    if(!filename.length())
        return;

    QPixmap pix(filename);
    if(pix.isNull())
    {
        QMessageBox::critical(this, tr("Wrong image"), tr("Can't open specified image."));
        return;
    }

    m_ui->iconLbl->setPixmap(pix);
    m_ui->pathEdit->setText(filename);
}

void CAddSectionDialog::setItem(CTreeItem *item)
{
    if(!item)
        return;

    debug("Setting item");

    m_item = item;
    if(item->icon_id().length())
    {
        debug("Standard icon: " + item->icon_id());
        QModelIndex index = m_model->index(m_model->row(item->icon_id()), 0);
        debug("Row: " + QString::number(index.row()));
        if(index.isValid())
            m_ui->listView->setCurrentIndex(index);
    }
    else
    {
        QPixmap pix;
        pix.loadFromData(item->icon().toByteArray());

        m_ui->iconLbl->setPixmap(pix);
    }

    m_ui->nameEdit->setText(item->name().toString());
}
